const nunjucks = require('nunjucks');

function templating(path) {

  let env = new nunjucks.Environment(
    new nunjucks.FileSystemLoader(path || 'views', {noCache:false, watch:true}),
    {autoescape: true, throwOnUndefined: false}
  )

  env.addFilter('CNY', function(val) {
    return '￥'+parseInt(val).toFixed(2);
  });

  env.addFilter('date', function(val) {
    const d = new Date(val);
    return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
  });

  return async (ctx, next) => {
    ctx.render = function (view, model) {
      ctx.response.body = env.render(
        view,
        Object.assign({}, ctx.state, model)
      )
      ctx.response.type = 'text/html'
    };
    await next();
  };
}

module.exports = templating;
